#include "user.h"
#define MAX_SIZE 255
uint8_t buffer[MAX_SIZE];
//uart1_tx-PA9,uart1_rx-PA10
void usart1_init()
{
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	
	GPIO_InitTypeDef gpioStruct;
	gpioStruct.GPIO_Mode=GPIO_Mode_AF;
	gpioStruct.GPIO_OType=GPIO_OType_PP;
	gpioStruct.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10;
	gpioStruct.GPIO_Speed=GPIO_Low_Speed;
	GPIO_Init(GPIOA,&gpioStruct);
	
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
	GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
	
	USART_InitTypeDef usartStruct;
	usartStruct.USART_BaudRate=115200;
	usartStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	usartStruct.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
	usartStruct.USART_Parity=USART_Parity_No;
	usartStruct.USART_StopBits=USART_StopBits_1;
	usartStruct.USART_WordLength=USART_WordLength_8b;
	USART_Init(USART1,&usartStruct);
	
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
	USART_Cmd(USART1,ENABLE);
	
	NVIC_InitTypeDef nvicStruct;
	nvicStruct.NVIC_IRQChannel=USART1_IRQn;
	nvicStruct.NVIC_IRQChannelCmd=ENABLE;
	nvicStruct.NVIC_IRQChannelPreemptionPriority=2;
	nvicStruct.NVIC_IRQChannelSubPriority=2;
	NVIC_Init(&nvicStruct);
	
}

void USART1_IRQHandler()
{
	if(USART_GetITStatus(USART1,USART_IT_RXNE)!=RESET)
	{
		static uint8_t length=0;
		uint8_t data=(uint8_t)USART_ReceiveData(USART1);
		USART_ClearITPendingBit(USART1,USART_IT_RXNE);
		if(data!='\r'&&data!='\n'&&length<MAX_SIZE)
		{
			buffer[length++]=data;
		}
		else
		{
			buffer[length]='\0';
			if(strcasecmp((char*)buffer,"openled")==0)
			{
				led_turn_on();
			}
			else if(strcasecmp((char*)buffer,"closeled")==0)
			{
				led_turn_off();
			}
			else if(strcasecmp((char*)buffer,"openbuzzer")==0)
			{
				buzzer_turn_on();
			}
			else if(strcasecmp((char*)buffer,"closebuzzer")==0)
			{
				buzzer_turn_off();
			}
			else
			{
				printf("invalid instrcution\r\n");
			}
			memset(buffer,0,length);
			length=0;
		}
		
	}
}
